package com.itboye.shop.me;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.shop.R;
import com.itboye.shop.app.MyApplication;
import com.itboye.shop.base.BaseActivity;
import com.itboye.shop.net.ResultEntity;
import com.itboye.shop.presenter.UserPresenter;
import com.itboye.shop.util.loadutil.CameraPopupWindow;
import com.itboye.shop.util.loadutil.Const;
import com.itboye.shop.util.loadutil.ImageCompress;
import com.itboye.shop.util.loadutil.IsUtilUid;
import com.itboye.shop.util.loadutil.MAlert;
import com.itboye.shop.util.loadutil.MultipartRequest;
import com.itboye.shop.util.loadutil.RoundImageView;
import com.itboye.shop.util.loadutil.SPUtils;
import com.itboye.shop.util.loadutil.XImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.shop.util.loadutil.MAlert.alert;

/**
 * 个人信息
 */
public class PersonalActivity extends BaseActivity implements Observer{
    TextView tvTitle;
    ImageView back;

    RoundImageView usericon_im;
    RelativeLayout user_image_layout, user_name_layout, user_name_renzheng, user_upadte_pass;
    TextView usericon_nicheng, usericon_rz;

    String nikeName;
    private Dialog dialog;// 自定义Dialog
    EditText dialog_et;

    public static String NICHENG = "nicheng";// 修成昵称成功之后的广播

    UserPresenter userPresenter;
    String uid;

    CameraPopupWindow cameraPopupWindow;
    // 使用相机拍照
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
    // 获取日期格式器对象

    private String picture_name;
    private String fileName;
    private String localSelectPath;
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择

    private String imgurls;
    String ISAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal);
        tvTitle.setText("个人信息");
        userPresenter = new UserPresenter(this);

        uid = (String) SPUtils.get(this, null, Const.ID, "");
        ISAuth = (String) SPUtils.get(this, null, Const.ISAUTH, "");
        if (ISAuth.equals("0")) {
            usericon_rz.setText("未认证");
        } else if (ISAuth.equals("1")) {
            usericon_rz.setText("已认证");
        } else {
            usericon_rz.setText("认证中");
        }
        XImageLoader.load(Const.IMAGE_HEAD + IsUtilUid.isHead(),
                usericon_im);
        read();
        showExtraDialog();
        IntentFilter filter1 = new IntentFilter("ISAUTH");
        registerReceiver(nichengBroadcastReceiver, filter1);

        isCameraPermission(this,1);
    }
    BroadcastReceiver nichengBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            ISAuth = (String) SPUtils.get(MyApplication.instatnce, null, Const.ISAUTH, "");
            if (ISAuth.equals("0")) {
                usericon_rz.setText("未认证");
            } else if (ISAuth.equals("1")) {
                usericon_rz.setText("已认证");
            } else {
                usericon_rz.setText("认证中");
            }
        };
    };
    /**
     * 加入数据
     */
    private void read() {
        nikeName = (String) SPUtils.get(this, null,
                Const.NICK, "");
        if (!nikeName.equals("")) {
            usericon_nicheng.setText(nikeName);
        } else {
            usericon_nicheng.setText("未设置");
        }
        String head = (String) SPUtils.get(this, null, Const.HEAD, "");
        if (head != null) {
            XImageLoader.load(Const.IMAGE_HEAD + IsUtilUid.isHead(),
                    usericon_im);
        } else {
            usericon_im.setImageResource(R.drawable.default_head);
        }

    }
    /**
     * 自定义Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(PersonalActivity.this, R.style.rel_dialog);
        View view = LayoutInflater.from(PersonalActivity.this).inflate(
                R.layout.user_shezhi, null);
        dialog.setContentView(view);
        dialog_et = (EditText) view.findViewById(R.id.dialog_et);

        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        user_title.setText("修改昵称");
        dialog_et.setText(nikeName);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                userPresenter.upadtaInformation(uid, "nickname", dialog_et.getText().toString().trim());
                showProgressDialog("修改中,请稍后", true);

            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }
    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.user_image_layout://头像
                cameraPopupWindow = new CameraPopupWindow(
                        PersonalActivity.this, onclicklister);
                cameraPopupWindow.showAtLocation(view, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.user_name_layout://昵称
                dialog.show();
                break;
            case R.id.user_name_renzheng://认证
                ISAuth = (String) SPUtils.get(MyApplication.instatnce, null, Const.ISAUTH, "");
                if (ISAuth.equals("0")) {
                    usericon_rz.setText("未认证");
//                    intent = new Intent(this, DriverRenZhengActivity.class);
//                    startActivity(intent);
                } else if (ISAuth.equals("1")) {
                    usericon_rz.setText("已认证");
                } else {
                    usericon_rz.setText("认证中");
                }

                break;
            case R.id.user_upadte_pass://修改密码
//                intent = new Intent(this, UpadtePassActivity.class);
//                startActivity(intent);
                break;
            default:
                break;
        }
    }
    private View.OnClickListener onclicklister = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.open_camera:
                    /**
                     * 打开照相机
                     */
                    String state = Environment.getExternalStorageState();
                    if (state.equals(Environment.MEDIA_MOUNTED)) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent,
                                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    } else {
                        MAlert.alert("请确认是否插入SD卡",Gravity.CENTER);
                    }
                    break;
                case R.id.pick_image:
                    // new PhotoSelectFragment(new PhotoSelect(),
                    // 6 - imgContainer.getChildCount() + 1).show(
                    // getSupportFragmentManager(), null);
                    // 激活系统图库，选择一张图片
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                    break;

                default:
                    break;
            }
        }

    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
                && resultCode == RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                return;
            }

            picture_name = android.text.format.DateFormat.format(
                    "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
                    + ".jpg";
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            File file = new File("/sdcard/Image/");
            file.mkdirs();// 创建文件夹
            fileName = "/sdcard/Image/" + picture_name;

            FileOutputStream b = null;
            try {
                if (b == null) {
                    b = new FileOutputStream(fileName);
                    Log.d("fileOutputStreams", b + "");
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    Log.d("fileOutputStream", b + "");
                    onImage(fileName);
                    Bitmap bm = BitmapFactory.decodeFile(fileName);
                    usericon_im.setImageBitmap(bm);
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
//            UploadImage.getInstance().execute(fileName, this);
            cameraPopupWindow.dismiss();
        } else if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                /**
                 * 当选择的图片不为空的话，在获取到图片的途径
                 */
                Uri selectedImage = data.getData();
                localSelectPath = null;

                localSelectPath = getRealPathFromURI(selectedImage);
                localSelectPath = ImageCompress.compress(localSelectPath);

                onImage(localSelectPath);
            }

        } else if (requestCode == IMAGE_COMPLETE) {
//            UploadImage.getInstance().execute(localSelectPath, this);
            cameraPopupWindow.dismiss();
        }
    };

    public static final int IMAGE_COMPLETE = 6; // 结果

    /**
     *  该方法用于获取文件的真实路径从URI
     */
    public String getRealPathFromURI(Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = this.managedQuery(contentUri, proj, null, null,
                    null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }
    public void onImage(String str) {
        showProgressDialog("头像上传中....", true);
        File files = new File(str);
        if (str == null) {
            alert("请上传相关图片",Gravity.CENTER);
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("uid", IsUtilUid.isUid());
        params.put("type", "avatar");

        MultipartRequest multipartRequest = new MultipartRequest(
                Const.IMAGE_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());
                        allInfoFromJson(arg0.toString());

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                alert(arg0,Gravity.CENTER);
            }
        }, "image", files, params);
        MyApplication.addRequest(multipartRequest);
    }

    public void allInfoFromJson(String jsonStr) {
        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = (JSONObject) jsonArray.get(i);

                String busLine = jsonObject.getString("imgurl");
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);

                String time = String.valueOf((int) (Math.random() * 10));
                MAlert.alert("上传成功!",Gravity.CENTER);
                SPUtils.put(MyApplication.instatnce, null,
                        Const.HEAD, busName);
                XImageLoader.load(Const.IMAGE_HEAD + busName,
                        usericon_im);

                try {
                    closeProgressDialog();
                } catch (Exception e) {
                    // TODO: handle exception
                }
                // 发送广播更新头像
                Intent intent2 = new Intent(PersonalActivity.NICHENG);
                sendBroadcast(intent2);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.updata_xinxi_success) {
                alert(entity.getData(),Gravity.CENTER);
                usericon_nicheng.setText(dialog_et.getText().toString().trim());
                SPUtils.put(this, null,
                        Const.NICK, dialog_et.getText().toString().trim());
                dialog.dismiss();

                Intent intent = new Intent(NICHENG);
                sendBroadcast(intent);
            }
            if (entity.getEventType() == UserPresenter.updata_xinxi_fail) {
                alert(entity.getData(),Gravity.CENTER);
                dialog.dismiss();
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }

    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    public static boolean isCameraPermission(Activity context, int requestCode){
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission!= PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }
}
